<template>
  <div class="wang-editor">
    <Toolbar
      ref="toolbar"
      class="toolbar"
      :editor="editor"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      ref="editor"
      v-model="html"
      class="editor"
      :style="{ height: `${height}px` }"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="onCreated"
      @onChange="fileChange"
    />
  </div>
</template>
<script>
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css";
import { getPublicConfig } from "libs/getPublicConfig";
import util from "libs/util";
import emitter from "element-ui/src/mixins/emitter";

export default {
  name: "WangEditor",
  components: { Editor, Toolbar },
  mixins: [emitter],
  model: {
    event: "change",
  },
  props: {
    value: {
      type: String,
      default: "",
    },
    // 最大图片尺寸
    maxFileSize: {
      type: Number,
      default: 20,
    },
    // 容器高度
    height: {
      type: Number,
      default: 1000,
    },
    // 编辑器类型
    mode: {
      type: String,
      default: "default",
      validator: (s) => ["default", "simple"].includes(s),
    },
  },
  data() {
    return {
      editor: null,
      html: "",
      toolbarConfig: {
        // 排除的菜单
        excludeKeys: ["fullScreen", "group-video", "codeBlock", "emotion"],
      },
      editorConfig: {
        placeholder: "请输入",
        MENU_CONF: {
          uploadImage: {},
        },
      },
    };
  },
  computed: {
    headers() {
      return {
        Authorization: util.cookies.get("token"),
        affiliationApp: getPublicConfig({
          key: "affiliationApp",
        }),
        affiliationAppType: getPublicConfig({
          key: "affiliationAppType",
        }),
      };
    },
  },
  watch: {
    value(val) {
      this.html = this.value;
      this.dispatch("ElFormItem", "el.form.change", val);
    },
  },
  created() {
    this.html = this.value;
    this.setUploadConfig();
  },
  beforeDestroy() {
    const editor = this.editor;
    if (editor === null) return;
    editor.destroy();
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor);
    },
    /**
     * 设置上传配置
     */
    setUploadConfig() {
      let api = getPublicConfig({ key: "api" });
      if (!api.endsWith("/")) api += "/";
      let that = this;
      this.editorConfig.MENU_CONF["uploadImage"] = {
        server: `${api}sys/file/upload/inhandle`,
        fieldName: "file",
        maxFileSize: this.maxFileSize * 1024 * 1024,
        maxNumberOfFiles: 10,
        allowedFileTypes: ["image/*"],
        metaWithUrl: false,
        headers: this.headers,
        base64LimitSize: 5 * 1024,
        onBeforeUpload(files) {
          return files; // 返回哪些文件可以上传
        },
        onProgress() {},
        onSuccess() {},
        onFailed() {},
        onError(file, err) {
          // 其他的报错，等遇到了再加
          if (err.message.includes("exceeds maximum allowed size")) {
            that.$message.error(`最大只能上传${that.maxFileSize}M的图片，请检查`);
          } else {
            that.$message.error("图片上传失败");
          }
        },
        customInsert(res, insertFn) {
          const {
            data: { viewPath },
            code,
            message,
          } = res;
          if (code === 200) {
            insertFn(viewPath);
          } else {
            that.$message.error(message);
          }
        },
      };
    },
    fileChange() {
      let html = this.html;
      if (html === "<p><br></p>") html = "";
      this.$emit("change", html);
    },
  },
};
</script>

<style lang="scss" scoped>
.wang-editor {
  border: 1px solid #ebeef5;
  .toolbar {
    border-bottom: 1px solid #ebeef5;
  }
  .editor {
    overflow-y: hidden;
  }
}
</style>
